<template>
  <el-container>
    <p
      v-if="$store.state.isRegistered"
      style="color:grey; text-align: center"
    >温馨提示：如果资料暂时不想填写可直接点击下一步跳过</p>
    <h2 v-else>用户详细资料</h2>
    <el-header>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basicInfo"></el-tab-pane>
        <el-tab-pane label="家庭成员" name="familyMembers"></el-tab-pane>
      </el-tabs>
    </el-header>
    <el-main>
      <el-form
        v-if="activeTab === 'basicInfo'"
        :model="basicInfo"
        :rules="basicInfoRules"
        ref="basicInfoForm"
      >
        <el-descriptions title="基本信息" border>
          <el-descriptions-item label="真实姓名">
            <el-form-item prop="realName">
              <span v-if="isPreview">{{ basicInfo.realName }}</span>
              <el-input v-else v-model="basicInfo.realName"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            <el-form-item prop="idCard">
              <span v-if="isPreview">{{ basicInfo.idCard }}</span>
              <el-input v-else v-model="basicInfo.idCard"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="出生年月">
            <el-form-item prop="birthDate">
              <span v-if="isPreview">{{ basicInfo.birthDate }}</span>
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-else
                v-model="basicInfo.birthDate"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            <el-form-item prop="phone">
              <span v-if="isPreview">{{ basicInfo.phone }}</span>
              <el-input v-else v-model="basicInfo.phone"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="身份证上传">
            <el-form-item prop="idUpload">
              <el-image
                v-if="isPreview"
                :src="basicInfo.idUpload"
                style="width: 100px; height: 100px;"
              ></el-image>
              <el-upload
                v-else
                action="/public-rental-housing-ssm/upload"
                list-type="text"
                :on-success="handleIdUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="户口本上传">
            <el-form-item prop="hukouUpload">
              <el-image
                v-if="isPreview"
                :src="basicInfo.hukouUpload"
                style="width: 100px; height: 100px;"
              ></el-image>
              <el-upload
                v-else
                action="/public-rental-housing-ssm/upload"
                list-type="text"
                :on-success="handleHukouUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="职业">
            <el-form-item prop="occupation">
              <span v-if="isPreview">{{ basicInfo.occupation }}</span>
              <el-input v-else v-model="basicInfo.occupation"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="工作单位">
            <el-form-item prop="workUnit">
              <span v-if="isPreview">{{ basicInfo.workUnit }}</span>
              <el-input v-else v-model="basicInfo.workUnit"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="上一年度的家庭全部收入">
            <el-form-item prop="annualIncome">
              <span v-if="isPreview">{{ basicInfo.annualIncome }}</span>
              <el-input v-else v-model="basicInfo.annualIncome"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="家庭人数">
            <el-form-item prop="familySize">
              <span v-if="isPreview">{{ basicInfo.familySize }}</span>
              <el-input type="number" v-else v-model="basicInfo.familySize"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="保障对象类型">
            <el-form-item prop="protectionType">
              <span v-if="isPreview">{{ basicInfo.protectionType }}</span>
              <el-select v-else v-model="basicInfo.protectionType" placeholder="请选择">
                <el-option label="A 类" value="A"></el-option>
                <el-option label="B 类" value="B"></el-option>
                <el-option label="C 类" value="C"></el-option>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="本市家庭人均住房面积（平方米）">
            <el-form-item prop="housingArea">
              <span v-if="isPreview">{{ basicInfo.housingArea }}</span>
              <el-input v-else v-model="basicInfo.housingArea"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="学历">
            <el-form-item prop="education">
              <span v-if="isPreview">{{ basicInfo.education }}</span>
              <el-input v-else v-model="basicInfo.education"></el-input>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="毕业证书上传">
            <el-form-item prop="graduationCertificate">
              <el-image
                v-if="isPreview"
                :src="basicInfo.graduationCertificate"
                style="width: 100px; height: 100px;"
              ></el-image>
              <el-upload
                v-else
                action="/public-rental-housing-ssm/upload"
                list-type="text"
                :on-success="handleGraduationUpload"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="申请的公租房区域">
            <el-form-item prop="requestedArea">
              <span v-if="isPreview">{{ basicInfo.requestedArea }}</span>
              <el-popover v-else placement="right" width="270" trigger="click">
                <div>
                  省份：
                  <el-select
                    slot="reference"
                    @change="fetchCities"
                    v-model="province"
                    placeholder="请选择省"
                  >
                    <el-option
                      v-for="item in provinces"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <br />城市：
                  <el-select
                    slot="reference"
                    @change="fetchAreas"
                    v-model="city"
                    placeholder="请选择市"
                  >
                    <el-option
                      v-for="item in cities"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                  <br />区域：
                  <el-select slot="reference" v-model="basicInfo.requestedArea" placeholder="请选择区域">
                    <el-option
                      v-for="item in areas"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </div>
                <el-button @click="areaSelect" size="small" type="primary" slot="reference">点击选择</el-button>
              </el-popover>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item label="备注信息">
            <el-form-item prop="remarks">
              <span v-if="isPreview">{{ basicInfo.remarks }}</span>
              <el-input v-else v-model="basicInfo.remarks"></el-input>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>

      <div v-if="activeTab === 'familyMembers'">
        <el-button type="primary" @click="addFamilyMember" v-if="!isPreview">添加家庭成员</el-button>
        <el-button type="danger" @click="deleteFamilyMember" v-if="!isPreview">删除家庭成员</el-button>
        <el-form :model="form" :rules="rules" ref="familyForm">
          <el-table
            :data="form.familyMembers"
            ref="familyTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" v-if="!isPreview"></el-table-column>
            <el-table-column prop="realName" label="真实姓名" width="120">
              <template slot-scope="scope">
                <el-form-item :prop="'familyMembers.' + scope.$index + '.realName'">
                  <span v-if="isPreview">{{ scope.row.realName }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.realName"
                    @blur="validateField('familyMembers.' + scope.$index + '.realName')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="idCard" label="身份证号" width="150">
              <template slot-scope="scope">
                <el-form-item :prop="'familyMembers.' + scope.$index + '.idCard'">
                  <span v-if="isPreview">{{ scope.row.idCard }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.idCard"
                    @blur="validateField('familyMembers.' + scope.$index + '.idCard')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="birthDate" label="出生年月" width="150">
              <template slot-scope="scope">
                <el-form-item :prop="'familyMembers.' + scope.$index + '.birthDate'">
                  <span v-if="isPreview">{{ scope.row.birthDate }}</span>
                  <el-date-picker
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    v-else
                    v-model="scope.row.birthDate"
                    type="date"
                    placeholder="选择日期"
                    @change="validateField('familyMembers.' + scope.$index + '.birthDate')"
                  ></el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="150">
              <template slot-scope="scope">
                <el-form-item :prop="'familyMembers.' + scope.$index + '.phone'">
                  <span v-if="isPreview">{{ scope.row.phone }}</span>
                  <el-input
                    v-else
                    v-model="scope.row.phone"
                    @blur="validateField('familyMembers.' + scope.$index + '.phone')"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="idUpload" label="身份证上传" width="100">
              <template slot-scope="scope">
                <el-image
                  v-if="isPreview"
                  :src="scope.row.idUpload"
                  style="width: 100px; height: 100px;"
                ></el-image>
                <el-upload
                  v-else
                  action="/public-rental-housing-ssm/upload"
                  list-type="text"
                  :on-success="(response, file) => handleFamilyIdUpload(response, file, scope.$index)"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column prop="hukouUpload" label="户口本上传" width="100">
              <template slot-scope="scope">
                <el-image
                  v-if="isPreview"
                  :src="scope.row.hukouUpload"
                  style="width: 100px; height: 100px;"
                ></el-image>
                <el-upload
                  v-else
                  action="/public-rental-housing-ssm/upload"
                  list-type="text"
                  :on-success="(response, file) => handleFamilyHukouUpload(response, file, scope.$index)"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column prop="occupation" label="职业" width="120">
              <template slot-scope="scope">
                <el-form-item :prop="'familyMembers.' + scope.$index + '.occupation'">
                  <span v-if="isPreview">{{ scope.row.occupation }}</span>
                  <el-select
                    v-else
                    v-model="scope.row.occupation"
                    placeholder="请选择"
                    @change="validateField('familyMembers.' + scope.$index + '.occupation')"
                  >
                    <el-option label="退休" value="退休"></el-option>
                    <el-option label="失业" value="失业"></el-option>
                    <el-option label="学生" value="学生"></el-option>
                    <el-option label="在职" value="在职"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="relationship" label="与申请本人的关系" width="150">
              <template slot-scope="scope">
                <el-form-item :prop="'familyMembers.' + scope.$index + '.relationship'">
                  <span v-if="isPreview">{{ scope.row.relationship }}</span>
                  <el-select
                    v-else
                    v-model="scope.row.relationship"
                    placeholder="请选择"
                    @change="validateField('familyMembers.' + scope.$index + '.relationship')"
                  >
                    <el-option label="父母" value="父母"></el-option>
                    <el-option label="子女" value="子女"></el-option>
                    <el-option label="夫妻" value="夫妻"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!isPreview" label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="danger" @click="removeFamilyMember(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
    </el-main>
    <el-footer v-if="basicInfo.status==='保存' || basicInfo.status== undefined">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="success" @click="preview">预览</el-button>
      <el-button type="danger" @click="submit">提交</el-button>
    </el-footer>
    <el-footer v-else>
      <p v-if="basicInfo.status === '未审核'">您的资料审核中，请耐心等待！</p>
      <p v-if="basicInfo.status === '已审核'">您的资料已审核通过！</p>
    </el-footer>
  </el-container>
</template>
  
  <script>
export default {
  data() {
    return {
      activeTab: "basicInfo",
      basicInfo: {
        realName: "",
        idCard: "",
        birthDate: "",
        phone: "",
        idUpload: "",
        hukouUpload: "",
        occupation: "",
        workUnit: "",
        annualIncome: "",
        familySize: "",
        protectionType: "",
        housingArea: "",
        education: "",
        graduationCertificate: "",
        requestedArea: "",
        remarks: ""
      },
      basicInfoRules: {
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/,
            message: "身份证号格式不正确",
            trigger: "blur"
          }
        ],
        birthDate: [
          { required: true, message: "出生年月不能为空", trigger: "change" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur"
          }
        ],
        idUpload: [
          { required: true, message: "请上传身份证", trigger: "change" }
        ],
        hukouUpload: [
          { required: true, message: "请上传户口本", trigger: "change" }
        ],
        occupation: [
          { required: true, message: "职业不能为空", trigger: "blur" }
        ],
        workUnit: [
          { required: true, message: "工作单位不能为空", trigger: "blur" }
        ],
        annualIncome: [
          {
            required: true,
            message: "上一年度的家庭全部收入不能为空",
            trigger: "blur"
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "收入格式不正确",
            trigger: "blur"
          }
        ],
        familySize: [
          { required: true, message: "家庭人数不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "家庭人数必须为数字", trigger: "blur" }
        ],
        protectionType: [
          { required: true, message: "保障对象类型不能为空", trigger: "change" }
        ],
        housingArea: [
          {
            required: true,
            message: "本市家庭人均住房面积不能为空",
            trigger: "blur"
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: "面积格式不正确",
            trigger: "blur"
          }
        ],
        education: [
          { required: true, message: "学历不能为空", trigger: "blur" }
        ],
        graduationCertificate: [
          { required: true, message: "请上传毕业证书", trigger: "change" }
        ],
        requestedArea: [
          {
            required: true,
            message: "申请的公租房区域不能为空",
            trigger: "change"
          }
        ],
        remarks: [
          { required: true, message: "备注信息不能为空", trigger: "blur" }
        ]
      },
      province: "",
      provinces: [],
      city: "",
      cities: [],
      areas: [],
      form: {
        familyMembers: []
      },
      rules: {
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/,
            message: "身份证号格式不正确",
            trigger: "blur"
          }
        ],
        birthDate: [
          { required: true, message: "出生年月不能为空", trigger: "change" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: "blur"
          }
        ],
        occupation: [
          { required: true, message: "职业不能为空", trigger: "change" }
        ],
        relationship: [
          {
            required: true,
            message: "与申请本人的关系不能为空",
            trigger: "change"
          }
        ]
      },
      selectedFamilyMembers: [],
      isPreview: false,
      url: "http://119.91.209.28:18008/public-rental-housing-ssm"
    };
  },
  mounted() {
    this.autoFill();
  },
  methods: {
    validateField(prop) {
      this.$refs.familyForm.validateField(prop);
    },
    autoFill() {
      if (this.$store.state.isRegistered) {
        this.$confirm("是否需要自动填充已注册的信息？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.basicInfo.tenant = this.$store.state.registerTenant.account;
            this.basicInfo.realName = this.$store.state.registerTenant.name;
            this.basicInfo.idCard = this.$store.state.registerTenant.idCard;
            this.basicInfo.phone = this.$store.state.registerTenant.phone;
          })
          .catch(() => {
            this.$store.commit("setRegisterTenant", null);
          });
      } else if (this.$store.state.isLogin) {
        this.$axios
          .post("tenant/getInfo", {
            account: this.$store.state.loginTenant.account
          })
          .then(res => {
            if (res.data.code === 200) {
              this.basicInfo = res.data.data.tenantInfoList[0];
              this.form.familyMembers = res.data.data.tenantFamilyList;
              if (this.basicInfo.status != "保存") {
                this.isPreview = true;
              }
            }
          });
      }
    },
    areaSelect() {
      this.fetchProvinces();
    },
    fetchProvinces() {
      this.$axios.post("area/province", { none: "none" }).then(res => {
        if (res.data.code === 200) {
          this.provinces = [];
          res.data.data.forEach(province => {
            this.provinces.push({ value: province.name, label: province.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    fetchCities() {
      this.city = "";
      this.$axios.post("area/city", { province: this.province }).then(res => {
        if (res.data.code === 200) {
          this.cities = [];
          res.data.data.forEach(city => {
            this.cities.push({ value: city.name, label: city.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    fetchAreas() {
      this.basicInfo.rentalArea = "";
      this.$axios
        .post("area/query", {
          province: this.province,
          city: this.city,
          name: ""
        })
        .then(res => {
          if (res.data.code === 200) {
            this.areas = [];
            res.data.data.forEach(area => {
              this.areas.push({ value: area.name, label: area.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    addFamilyMember() {
      this.form.familyMembers.push({
        realName: "",
        idNumber: "",
        birthDate: "",
        phoneNumber: "",
        idUpload: "",
        hukouUpload: "",
        occupation: "",
        relationship: ""
      });
    },
    handleSelectionChange(val) {
      this.selectedFamilyMembers = val;
    },
    deleteFamilyMember() {
      if (this.selectedFamilyMembers.length === 0) {
        this.$message.warning("请选择要删除的家庭成员");
        return;
      }
      this.selectedFamilyMembers.forEach(member => {
        const index = this.form.familyMembers.indexOf(member);
        if (index > -1) {
          this.form.familyMembers.splice(index, 1);
        }
      });

      this.$refs.familyTable.clearSelection();
      this.selectedFamilyMembers = [];
    },
    removeFamilyMember(index) {
      this.form.familyMembers.splice(index, 1);
    },
    confirm(status) {
      const account = this.$store.state.isLogin
        ? this.$store.state.loginTenant.account
        : this.$store.state.registerTenant.account;
      this.basicInfo.status = status;
      this.form.familyMembers.forEach(member => {
        member.tenant = account;
      });
      this.$store.dispatch("registerTenant", null);
      const payload = {
        basicInfo: this.basicInfo,
        familyMembers: this.form.familyMembers
      };
      if (status === "未审核") {
        status = "提交";
        this.isPreview = true;
      }
      this.$axios
        .post("tenant/saveInfo", payload)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success(`${status}成功`);
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    preview() {
      this.isPreview = !this.isPreview;
    },
    save() {
      this.confirm("保存");
    },
    submit() {
      console.log(this.$refs);
      this.$refs.basicInfoForm.validate(valid1 => {
        if (valid1) {
          if (this.form.familyMembers.length = 0) {
            this.$message.error("请添加家庭成员");
            return;
          }
          this.$confirm("您确定要提交吗，提交后将无法修改", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.confirm("未审核");
              this.autoFill();
            })
            .catch(() => {});
        } else {
          this.$message.error("请填写完整资料信息");
        }
      });
    },
    handleIdUpload(response) {
      this.basicInfo.idUpload = this.url + response;
      this.basicInfo.idCardImage = response;
    },
    handleHukouUpload(response) {
      this.basicInfo.hukouUpload = this.url + response;
      this.basicInfo.householdRegister = response;
    },
    handleGraduationUpload(response) {
      this.basicInfo.graduationCertificate = this.url + response;
      this.basicInfo.diploma = response;
    },
    handleFamilyIdUpload(response, file, index) {
      this.form.familyMembers[index].idUpload = this.url + response;
      this.form.familyMembers[index].idCardImage = response;
    },
    handleFamilyHukouUpload(response, file, index) {
      this.form.familyMembers[index].hukouUpload = this.url + response;
      this.form.familyMembers[index].householdRegister = response;
    }
  }
};
</script>
  
  <style scoped>
.el-container {
  height: 100%;
}
.el-header,
.el-footer {
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-main {
  padding: 20px;
}
.el-container {
  height: 100%;
}
.el-form-item {
  margin: 0;
}
</style>